<script setup lang="ts">
import { ref, watch } from 'vue';
import _ from 'lodash';
import useSWRV from 'swrv';
import axios from 'redaxios';
import { useRoute } from 'vue-router';
import { useIntervalFn } from '@vueuse/core';
import CurvePoints from '../components/CurverPoints.vue';
import { IconMenu2, IconEyeClosed } from '@tabler/icons-vue';
import { FanListResponse, ProfileInfoResponse, ProfileInfoResponseItem, TempatureListResponse, TempatureListResponseItem } from '../webApi';
import PolylineZone from '../components/PolylineZone.vue';
const apiRefreshCounter = ref(0);
const route = useRoute();
const queryApiAddr = ref('/api/fan/list?');
watch([route, apiRefreshCounter], function () {
    queryApiAddr.value = '/api/fan/list?' + "&c=" + apiRefreshCounter.value;
});
const { pause, resume, isActive } = useIntervalFn(async () => {
    await refreshDetailWebData();
}, 1000);


function refreshDetailWebData() {
    apiRefreshCounter.value += 1;
}

const { data, error } = useSWRV(queryApiAddr, async () => {
    // return { success: false, list: [] };
    const wiFanList = await axios({
        method: 'GET',
        url: `/api/fan/list`,
        headers: {
        },
    });
    const wiProfileInfo = await axios({
        method: 'GET',
        url: `/api/fan/profile`,
        headers: {
        },
    });
    const wiTempatureList = await axios({
        method: 'GET',
        url: `/api/tempature/list`,
        headers: {
        },
    });

    const dictOfProfile = _.keyBy((wiProfileInfo.data as ProfileInfoResponse).Data, 'SensorId');
    const tpList = (wiTempatureList.data as TempatureListResponse).Data
    return {
        fanList: (wiFanList.data as FanListResponse).Data.map(item => ({
            ...item,
            profile: dictOfProfile[item.Id] || {
                "CustomName": '',
                "SensorId": item.Id,
                "TemperaureSrcId": tpList[0].Id,
                "IsControl": false,
                "ControlWays": '折线图',
                "curvePoints": [],
            },
        })),
        profileInfo: wiProfileInfo.data as ProfileInfoResponse,
        tempatureList: tpList,
    };
}, {
    revalidateOnFocus: true,
});


function findTempature(ritem: ProfileInfoResponseItem): number | undefined {
    return data.value?.tempatureList.find(item => item.Id === ritem.TemperaureSrcId)?.Val;
}
async function setProfileFlag(ritem: ProfileInfoResponseItem, flags: { enableControl?: boolean, hideInMain?: boolean }) {
    await axios.post("/api/profile/setFlag", {
        id: ritem.SensorId,
        ...flags,
    });
    refreshDetailWebData();
}

function needShow(item: ProfileInfoResponseItem) {
    if (route.path.includes("fanListInvisible")) {
        return !!item?.HideInMain;
    }
    return !item?.HideInMain;
}


</script>

<template>
    <div v-if="error">failed to load</div>
    <div v-if="!data">loading...</div>
    <div v-else class="list">
        <n-grid x-gap="12" y-gap="12" cols="1 1000:2 ">
            <n-gi v-for="item in data.fanList.filter(x => needShow(x.profile))" :key="item.Id">
                <n-card title="">
                    <n-grid :cols="20" x-gap="20">
                        <n-gi span="8">
                            <div class="light-green">
                                <n-ellipsis>
                                    <n-text depth="3">
                                        {{ item.Id }}
                                    </n-text>
                                </n-ellipsis>
                                <div style="width: 1px; height: 20px;"></div>

                                <n-text depth="3"> 名称 </n-text>
                                <div> {{ item.Name }} </div>
                                <div class="hh5"></div>

                                <n-text depth="3"> 转速 </n-text>
                                <div>
                                    {{ item.DetailDesc }}
                                    <n-progress type="line" :show-indicator="false"
                                        :percentage="(item.ControlValue - item.ControlValueMin) / (item.ControlValueMax - item.ControlValueMin) * 100"
                                        :border-radius="4" :fill-border-radius="0" />
                                </div>
                                <div class="hh5"></div>

                                <n-text depth="3"> 启用控制 </n-text>
                                <div>
                                    <n-switch :round="false" :value="item.profile?.IsControl"
                                        @click="() => setProfileFlag(item.profile, { enableControl: !item.profile?.IsControl })">
                                        <template #checked>
                                            启用控制
                                        </template>
                                        <template #unchecked>
                                            停用控制
                                        </template>
                                    </n-switch>
                                </div>
                                <div class="hh5"></div>


                                <div class="hh5"></div>
                                <n-text depth="3" style="width: 80%;">
                                    <n-dropdown trigger="click" :options="[
                                        {
                                            label: !item.profile?.HideInMain ? '从主页隐藏' : '显示在主页',
                                            key: 'toggle-visible',
                                        },
                                        {
                                            label: 'more...',
                                            key: 'more',
                                            disabled: true,
                                        },

                                    ]"
                                        @select="() => setProfileFlag(item.profile, { hideInMain: !item.profile?.HideInMain })">
                                        <n-button quaternary type="info" style="padding: 0;" size="small">
                                            <IconMenu2 /> 更多选项
                                        </n-button>
                                    </n-dropdown>
                                </n-text>
<!-- 
                                <n-popover placement="bottom-start" trigger="click" content-style="padding: 0">
                                    <template #trigger>
                                        <n-button quaternary type="info" style="padding: 0;" size="small">
                                            <IconMenu2 /> 更多选项
                                        </n-button>
                                    </template>
                                    <div style="padding: 0">
                                        <n-button
                                            @class="() => setProfileFlag(item.profile, { hideInMain: !item.profile?.HideInMain })">
                                            {{ !item.profile?.HideInMain ? '从主页隐藏' : '显示在主页' }}
                                        </n-button>
                                    </div>
                                </n-popover> -->


                            </div>
                        </n-gi>
                        <n-gi span="12">
                            <div>
                                <n-tabs type="segment" size="small" :value="item.profile.ControlWays">
                                    <n-tab-pane name="折线图" tab="折线图">
                                        <n-select v-model:value="item.profile.TemperaureSrcId"
                                            :options="data.tempatureList?.map(item => ({ label: item.Desc, value: item.Id }))" />
                                        <div style="width: 100%; height: 8px;"></div>
                                        <PolylineZone :this-id="item.Id.split('/').join('')" :profile="item.profile"
                                            :tempature="findTempature(item.profile)" />
                                        <!-- {{ item.Id.split('/').join('') }} -->
                                        <!-- <CurvePoints :profile="item.profile" /> -->
                                    </n-tab-pane>
                                    <n-tab-pane name="固定" tab="固定（待开发）">
                                        “威尔！着火了！快来帮忙！”我听到女朋友大喊。现在一个难题在我面前——是恢复一个重要的
                                        Amazon 服务，还是救公寓的火。<br><br>
                                        我的脑海中忽然出现了 Amazon
                                        著名的领导力准则”客户至上“，有很多的客户还依赖我们的服务，我不能让他们失望！所以着火也不管了，女朋友喊我也无所谓，我开始
                                        debug 这个线上问题。
                                    </n-tab-pane>
                                </n-tabs>
                            </div>
                        </n-gi>
                    </n-grid>
                </n-card>

            </n-gi>
        </n-grid>
    </div>
</template>

<style scoped>
.list {
    display: block;
}

.hh5 {
    width: 1px;
    height: 32px;
}
</style>
